<template>
  <div class="containers">
    <div class="container">
      <div class="handle-box">
        <el-select v-model="take" @change="handleTakeChange" placeholder="请选择类型" size="mini" class="mr10">
          <el-option v-for="(item, index) in navlists" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="state" @change="handleStateChange" placeholder="请选择类型" size="mini" class="mr10">
          <el-option v-for="(item, index) in navlist" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="pay_type" @change="handlePayTypeChange" placeholder="请选择类型" size="mini" class="mr10">
          <el-option v-for="(item, index) in paylist" :key="item.id" :label="item.name" :value="item.id" v-if="item.id!=1&&item.id!=2">
          </el-option>
        </el-select>

        <el-select v-model="business_id" filterable clearable :filter-method="filterMethod"
          @clear="clear" @change="handleBusinessChange" placeholder="请选择商家" size="mini" class="mr10">
          <el-option v-for="(item, index) in businessList" :key="item.id" :label="item.name" :value="item.ID" >
          </el-option>
        </el-select>

        <el-date-picker class="mr10" style="width: 220px;"
          v-model="value2"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="mini"
          align="right" @change="changeTime">
        </el-date-picker>
        <el-input v-model="keyword" placeholder="订单号/用户电话/收货人/商品名称" style="width: 220px;" class="handle-input mr10" size="mini"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="getDataPage"  size="mini">搜索</el-button>
        <el-button type="primary" @click="exportExcel" class="mr10" size="mini">导出</el-button>
      </div>

      <el-table :data="tableData" class="table" ref="multipleTable" header-cell-class-name="table-header" border size="mini"
        @selection-change="handleSelectionChange" v-loading="loading" id="out-table" :height="$tableHight">
        <el-table-column type="index" width="55" label="序号" align="center" ></el-table-column>
        <el-table-column prop="business.name" label="商家" width="120"  show-overflow-tooltip></el-table-column>
        <el-table-column prop="order" label="订单号" width="180"></el-table-column>

        <el-table-column  label="商品名字" width="240" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ getFirstGoodsInfo(scope.row.goods, 'name') }}
          </template>
        </el-table-column>
        <el-table-column  label="商品数量" >
          <template slot-scope="scope">
            <div >
              {{ getFirstGoodsInfo(scope.row.goods, 'number') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column  label="商品价格" >
          <template slot-scope="scope">
            <div >
              {{ getFirstGoodsInfo(scope.row.goods, 'price') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="money" label="金额"></el-table-column>
        <el-table-column prop="freight" label="运费"></el-table-column>
        <el-table-column prop="user.nickname" label="购买用户" width="110"></el-table-column>
        <el-table-column prop="user.mobile" label="用户电话" width="110"></el-table-column>

        <el-table-column label="收货人" width="80">
          <template slot-scope="scope">
          {{scope.row.name}}
           </template>
        </el-table-column>
        <el-table-column label="收货人电话" width="110">
          <template slot-scope="scope">
            {{scope.row.mobile}}
          </template>

        </el-table-column>
        <el-table-column label="地址信息" show-overflow-tooltip width="300">
          <template slot-scope="scope">
            {{scope.row.address}}<i class="el-icon-document-copy" @click="copyAddress(scope.row)" style="cursor: pointer; margin-left: 5px;"></i>
          </template>
        </el-table-column>

        <el-table-column label="下单时间" align="center" width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            <div v-if="scope.row.pay_time">
              {{$clearTimer(scope.row.pay_time)}}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="支付方式" align="center">
          <template slot-scope="scope">
            {{ getPayTypeName(scope.row.pay_type) }}
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center">
          <template slot-scope="scope">
            {{ ORDER_STATES[scope.row.state] || '未知' }}
          </template>
        </el-table-column>

        <el-table-column label="提货方式" align="center">
          <template slot-scope="scope">
            {{ DELIVERY_TYPES[scope.row.take] || '未知' }}
          </template>
        </el-table-column>


        <!-- <el-table-column label="操作" width="180" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" :disabled="scope.row.state!==1"  size="mini" @click="cancelOrder(scope.row)">取消订单</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      <div class="pagination">

        <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange" :current-page="query.pageIndex"
          :page-sizes="[20, 30, 40, 50]" :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="pageTotal">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>

import excel from '../../utils/excel.js'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'

// 常量定义
const PAY_TYPES = {
  0: '余额',
  1: '积分',
  2: '微信',
  3: '支付宝',
  4: '银行卡'
}

const ORDER_STATES = {
  0: '待付款',
  1: '待发货',
  2: '待收货',
  3: '待评价',
  4: '完成',
  5: '售后',
  8:'已取消'
}

const DELIVERY_TYPES = {
  0: '快递',
  1: '自提'
}

// 支付方式名称映射数组
const PAY_TYPE_NAMES = [
  '消费券',
  '补贴券',
  '资产积分',
  '绿色积分记录',
  '权益值',
  '贡献值',
  '云仓积分'
];

export default {
  name: 'basetable',
  data() {
    return {
      PAY_TYPES,
      ORDER_STATES,
      DELIVERY_TYPES,
      query: {
        pageIndex: 1,
         pageSize: 20
      },
      state: 1,
      editVisible: false,
      pageTotal: 0,
      type: 0,
      take:-1,
      navlist: [
      {id:-1, name:'全部'},
      // {id:0, name:'待付款'},
      {id:1, name:'待发货'},
      {id:2, name:'待收货'},
      {id:3, name:'待评价'},
      {id:4, name:'完成'},
      {id:5, name:'售后'},
      {id:8, name:'已取消'},
      ],
      navlists: [
        {id:-1, name:'全部'},
        {id:0, name:'快递'},
        {id:1, name:'自提'},
      ],
      paylist: [
        {id:-1, name:'全部'},
        {id:0, name:'余额'},
        {id:3, name:'支付宝'},
        {id:4, name:'银行卡'},
      ],
      pay_type:-1,
      keyword: '',
      loading:false,
      tableData: [],
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        value2: '',
      start_time:'',
      end_time:'',
      businessList:[],
      business_id:''
    };
  },
  created() {
    this.getData()
    this.getBusinessList()
  },
  methods: {
    // 获取商品信息的辅助函数
    getFirstGoodsInfo(goods, field) {
      if (goods && goods.length > 0) {
        return goods[0][field] || '';
      }
      return field === 'number' || field === 'price' ? 0 : '';
    },

    // 获取支付方式名称
    getPayTypeName(payType) {
      return PAY_TYPE_NAMES[payType] || '未知';
    },

    // 复制地址信息
    copyAddress(row) {
      const text = `${row.name || ''}${row.mobile || ''}${row.address || ''}`;
      this.copy(text);
    },

    filterMethod(e) {
      this.getBusinessList(e)
    },
    clear() {
      this.getBusinessList()
      this.business_id = ''
      this.query.pageIndex = 1 // 重置到第一页
      this.getData()

    },
    getBusinessList(e) {
      this.request('admin/businessList/', 'get', {
        page: 1,
        size: 20,
        keyword:e,
      }).then(res => {
        this.businessList = res.data.data
      })
    },
    setImg(row){
      return
    },
    // 使用现代 Clipboard API 或回退到传统方法
    async copy(text) {
      try {
        if (navigator.clipboard && window.isSecureContext) {
          await navigator.clipboard.writeText(text);
        } else {
          // 回退到传统方法
          const textArea = document.createElement("textarea");
          textArea.value = text;
          textArea.style.position = "fixed";
          textArea.style.opacity = "0";
          document.body.appendChild(textArea);
          textArea.select();
          document.execCommand('copy');
          document.body.removeChild(textArea);
        }
        this.$message.success('复制成功');
      } catch (error) {
        console.error('复制失败:', error);
        this.$message.error('复制失败');
      }
    },
    getDataPage() {
      this.query.pageIndex = 1; // 重置到第一页
      this.getData();
    },
    // 提货方式变更
    handleTakeChange(val) {
      this.take = val;
      this.query.pageIndex = 1; // 重置到第一页
      this.getData();
    },
    // 订单状态变更
    handleStateChange(val) {
      this.state = val;
      this.query.pageIndex = 1; // 重置到第一页
      this.getData();
    },
    // 支付方式变更
    handlePayTypeChange(val) {
      this.pay_type = val;
      this.query.pageIndex = 1; // 重置到第一页
      this.getData();
    },
    // 商家变更
    handleBusinessChange(val) {
      this.business_id = val;
      this.query.pageIndex = 1; // 重置到第一页
      this.getData();
    },
    exportExcel () {
      // 安全地获取token
      const token = localStorage.getItem('admin_token_sys');
      if (!token) {
        this.$message.error('未找到认证信息，请重新登录');
        return;
      }

      //导出
      this.$http({
        url: this.mainurl + 'admin/getShopOrder/',
        method: 'get',
        responseType: 'blob',
        params: {
          pay_type: this.pay_type,
          start_time: this.start_time,
          end_time: this.end_time,
          take: this.take,
          page: this.query.pageIndex,
          size: this.query.pageSize,
          state: this.state,
          keyword: this.keyword,
          business_id:this.business_id,
          code: 1,
        },
        headers: {
          'Content-Type': 'application/json',
          token: token
        }
      }).then(res => {
        try {
          FileSaver.saveAs(
            new Blob([res.data], { type: "application/octet-stream;charset=utf-8" }), "订单.xlsx")
        } catch (e) {
          if (typeof console !== "undefined") console.log(e, res.data);
        }
      }).catch(error => {
        console.error('导出失败:', error);
        this.$message.error('导出失败');
      });
    },
    //修改size值
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.query.pageSize = val
      this.query.pageIndex = 1 // 重置到第一页
      this.getData();
    },
    // 获取数据
    getData() {
      this.loading=true
      this.request('admin/getShopOrder/', 'get', {pay_type:this.pay_type,start_time:this.start_time,
        end_time:this.end_time,take:this.take, page: this.query.pageIndex, business_id:this.business_id,
        size: this.query.pageSize,state:this.state,keyword:this.keyword}).then(res => {
        this.tableData = res.data.data
        this.pageTotal = res.data.total
      }).catch(error => {
        console.error(error)
        this.$message.error('获取数据失败')
      }).finally(() => {
        this.loading=false
      })
    },
    // 发货
    handleEdit(e,state) {
      this.$router.push({ path: '/business/orderDetails', query: { id: e.order,state:state } });
    },
    cancel() {
      this.getData();
    },

    // 删除操作
    handleDelete(index, row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.request('admin/order/', 'delete', { ID: row.ID }).then(res => {
            if (res.errno == 0) {
              this.$message.success(res.errmsg);
              this.tableData.splice(index, 1)
              this.getData()
            } else {
              this.$message.error(res.errmsg);
            }
          }).catch(error => {
            console.error(error)
            this.$message.error('删除失败')
          });
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 订单取消
    cancelOrder(row) {
      this.$prompt('请在下方输入取消理由', '确定要取消吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /\S/,
        inputErrorMessage: '内容不能为空'
      }).then(({ value }) => {
        this.request("admin/cancelOrder/", "post", { order: row.order,reason:value }).then(
          (res) => {
            if(res.errno==0) {
              this.$message.success(res.errmsg);
              this.getData()
            }
          }
        );

      }).catch(() => {
        // 用户取消操作
      })
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 添加
    addregion() {
      this.$router.push({ path: '/commodity/addgoods' })
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, 'pageIndex', val);
      this.getData();
    },
    changeTime(e){//时间
      console.log(e)
      try {
        this.start_time=this.formatDate(e[0])
        this.end_time=this.formatDate(e[1])
      } catch (error) {
        this.start_time=''
        this.end_time=''
      }
      this.query.pageIndex = 1 // 重置到第一页
      this.getData()
    },
    formatTen(num) {
        return num > 9 ? (num + "") : ("0" + num);
    },
    formatDate(date) {
        var date = new Date(date)
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minute = date.getMinutes();
        var second = date.getSeconds();
        return year + "-" + this.formatTen(month) + "-" + this.formatTen(day)+ " " +this.formatTen(hour)+ ":" +this.formatTen(minute)+ ":" +this.formatTen(second);
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.el-upload--text {
  width: 200px !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;

  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  /* width: 100px; */
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 178px;
  display: block;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 60px;
  height: 60px;

  .el-image img {
    object-fit: cover;
  }
}

/* 设置分页按钮样式 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.table-td-thumb{
  margin: 0 !important;
}
.namelist{
  margin-left: 10px;
}
/* 使用 /deep/ 或 >>> 来穿透 scoped 样式 */
::v-deep .el-table th.el-table__cell {
  background-color: #f2f2f2;
  /* 设置表头颜色 */
  color: #333;
  /* 设置表头文字颜色 */
}
</style>
